import { HYDRATE } from "next-redux-wrapper";
import { AskTypes } from "redux/constants";

const initialState = {
  loading: false,
  data: null,
  error: null,
};

export const list = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    case AskTypes.QUESTION_LIST_REQUEST:
      return { ...state, ...{ loading: false, data: null, error: null } };
    case AskTypes.QUESTION_LIST_SUCCESS:
      return {
        loading: false,
        error: action.payload.message,
        data: action.payload.data,
      };
    case AskTypes.QUESTION_LIST_FAILURE:
      return {
        loading: false,
        error: action.payload,
        data: null,
      };
    default:
      return state;
  }
};

export const publish = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    case AskTypes.QUESTION_PUBLISH_REQUEST:
      return { ...state, ...{ loading: true, error: null, data: null } };
    case AskTypes.QUESTION_PUBLISH_SUCCESS:
      return {
        loading: false,
        error: action.payload.message,
        data: action.payload.data,
      };
    case AskTypes.QUESTION_PUBLISH_FAILURE:
      return { loading: false, error: action.payload, data: null };
    default:
      return state;
  }
};

export const detail = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    case AskTypes.QUESTION_DETAIL_REQUEST:
      return { ...state, ...{ loading: true, error: null, data: null } };
    case AskTypes.QUESTION_DETAIL_SUCCESS:
      return {
        loading: false,
        error: action.payload.message,
        data: action.payload.data,
      };
    case AskTypes.QUESTION_DETAIL_FAILURE:
      return { loading: false, error: action.payload, data: null };
    default:
      return state;
  }
};

export const edit = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    case AskTypes.QUESTION_EDIT_REQUEST:
      return { ...state, ...{ loading: true, error: null, data: null } };
    case AskTypes.QUESTION_EDIT_SUCCESS:
      return {
        loading: false,
        error: action.payload.message,
        data: action.payload.data,
      };
    case AskTypes.QUESTION_EDIT_FAILURE:
      return { loading: false, error: action.payload, data: null };
    default:
      return state;
  }
};

const ask = {
  list,
  publish,
  detail,
  edit,
};

export default ask;
